#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    server = new QLocalServer(this);

    // 告诉服务器监听传入连接的名字。如果服务器当前正在监听，那么将返回false。监听成功返回true，否则为false
    if (!server->listen("fortune")) {
        QMessageBox::critical(this, tr("Fortune Server"),
                            tr("Unable to start the server: %1.")
                            .arg(server->errorString()));
        close();
        return;
    }

    fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
             << tr("You've got to think about tomorrow.")
             << tr("You will be surprised by a loud noise.")
             << tr("You will feel hungry again in another hour.")
             << tr("You might have mail.")
             << tr("You cannot kill time without injuring eternity.")
             << tr("Computers are not intelligent. They only think they are.");

    // 有新客户端进行连接时，发送数据
    connect(server, SIGNAL(newConnection()), this, SLOT(sendFortune()));
}

// 发送数据
void Widget::sendFortune()
{
    // 从fortunes中随机取出一段字符串然后进行写入。
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << (quint16)0;
    out << /*fortunes.at(qrand() % fortunes.size())*/"helloworld!!!";
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    // nextPendingConnection()可以返回下一个挂起的连接作为一个连接的QLocalSocket对象。
    QLocalSocket *clientConnection = server->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));

    clientConnection->write(block);
    clientConnection->flush();
    clientConnection->disconnectFromServer();
}

Widget::~Widget()
{
    delete ui;
}
